<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function partitionLabels(S) {
      let map = new Map()
      let n = S.length;
      // 一. 记录字符最后出现的索引
      for (let i = 0; i < n; i++) {
        map.set(S[i], i)
      }
      let start = 0, end = 0
      let res = []
      // 二. 循环 更新end为当前遍历到的字符最后出现的 最大索引, 
      //一旦end和当前索引相同,说明这个片段中所有字符都在start-end片段内了, 加入结果集, 更新start
      for (let i = 0; i < n; i++) {
        end = Math.max(end, map.get(S[i]))
        if (end === i) {
          res.push(end - start + 1)
          start = i + 1
        }
      }
      return res
    };
    console.log(partitionLabels(s = "ababcbacadefegdehijhklij"))
  </script>
</body>

</html>